#include<iostream>
#include<string>
#include <cstring>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

void Usage(std::string a)
{
    std::cout<<"Usage:\n\t"<<a<<"ip address"<<" "<<"local port"<<std::endl;
}
int main(int argc,char *argv[])
{
    if(argc != 3)//./client ip地址 端口号
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    //client这边的步骤也差不多，需要注意的是，Udpclent不要显示的绑定，其首次发送数据时OS会自动随机的给client进行bind
    //创建socket
    int sockfd = socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd < 0)
    {
        std::cerr<<"socket error"<<std::endl;
        exit(2);
    }

    //填充 struct sockaddr_in
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_port=htons(serverport);
    server.sin_addr.s_addr=inet_addr(serverip.c_str());
    //少了步显示绑定
    std::string messagebuffer;
    //通信
    while(true)
    {
        std::cout<<"请输入#";
        getline(std::cin,messagebuffer);
        //先发送
        sendto(sockfd,messagebuffer.c_str(),messagebuffer.size(),0,(struct sockaddr*)&server,sizeof(server));

        //接收
        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        ssize_t n = recvfrom(sockfd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&peer,&len);
        if(n > 0)
        {
            buffer[n]=0;
            std::cout<<"服务端返回#"<<buffer<<std::endl;
        }
    }
    return 0;
}